package com.macro.mall.tiny.modules.pms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.api.ResultCode;
import com.macro.mall.tiny.modules.pms.model.PmsBrand;
import com.macro.mall.tiny.modules.pms.model.PmsPointLight;
import com.macro.mall.tiny.modules.pms.service.PmsBrandService;
import com.macro.mall.tiny.modules.pms.service.PmsPointLightService;
import com.macro.mall.tiny.security.util.MemberContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.sql.ResultSet;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tyrone
 * @since 2024-10-09
 */
@RestController
@RequestMapping("/pms/pmsPointLight")
@Api(tags = "PmsPointLightController")
@Tag(name = "PmsPointLightController", description = "指示灯")
public class PmsPointLightController {

    @Autowired
    private PmsPointLightService pmsPointLightService;

    @Autowired
    private PmsBrandService pmsBrandService;


    private static String ENDPOINT  = "https://document-1328890941.cos.ap-shanghai.myqcloud.com/" ;

    @ApiOperation("获取指示灯支持品牌")
    @GetMapping("/getBrand")
    public CommonResult<List<PmsBrand>> getBrand() {
        List<Integer> brandIds = pmsPointLightService.list(new QueryWrapper<PmsPointLight>().select("brand_id").groupBy("brand_id"))
                .stream().map(PmsPointLight::getBrandId).collect(Collectors.toList());
        List<PmsBrand> brandList = pmsBrandService.list(new QueryWrapper<PmsBrand>().in("id", brandIds));
        if (ObjectUtils.isEmpty(brandList)) {
            return CommonResult.success(Collections.emptyList());
        }
        return CommonResult.success(brandList);
    }

    @ApiOperation("根据品牌ID获取指示灯分类")
    @GetMapping("/getCategoryByBrandId")
    public CommonResult<List<String>> getCategoryByBrandId(Integer brandId) {
        List<PmsPointLight> list = pmsPointLightService.list(new QueryWrapper<PmsPointLight>()
                .select("category")
                .eq("brand_id", brandId).groupBy("category"));
        if (ObjectUtils.isEmpty(list)) {
            return CommonResult.success(Collections.emptyList());
        }
        return CommonResult.success(list.stream().map(PmsPointLight::getCategory).collect(Collectors.toList()));
    }


    @ApiOperation("获取指示灯详情")
    @GetMapping("/getDetailPointLight")
    public CommonResult<List<PmsPointLight>> getDetailPointLight(
            Integer brandId,
            String category) {

        if (MemberContext.getMember() == null) {
            return CommonResult.failed(ResultCode.UNAUTHORIZED);
        }
        if (MemberContext.getMember().getVip() == null || MemberContext.getMember().getVip().equals(0)) {
            return CommonResult.failed(ResultCode.NEED_VIP);
        }

        List<PmsPointLight> list = pmsPointLightService.list(new QueryWrapper<PmsPointLight>()
                .eq("brand_id", brandId)
                .eq("category", category));
        if (ObjectUtils.isEmpty(list)) {
            return CommonResult.success(Collections.emptyList());
        }
        list.sort(Comparator.comparing(PmsPointLight::getUrl));
        return CommonResult.success(list);
    }

    @ApiOperation("分页获取指示灯（万能接口） 支持 brandId category")
    @GetMapping("page")
    public CommonResult<List<PmsPointLight>> pagePointLight(Integer brandId, String category) {
        List<PmsPointLight> list = pmsPointLightService.list(new QueryWrapper<PmsPointLight>()
                .eq("brand_id", brandId)
                .eq("category", category));
        if (ObjectUtils.isEmpty(list)) {
            return CommonResult.success(Collections.emptyList());
        }
        list.sort(Comparator.comparing(PmsPointLight::getUrl));
        return CommonResult.success(list);
    }

    @ApiOperation("后台万能分页接口")
    @PostMapping("/list")
    public CommonResult<IPage<PmsPointLight>> listPointLight(@RequestBody PmsPointLightDTO dto) {
        Page<PmsPointLight> page = new Page<>(dto.getPageNum(), dto.getPageSize(), Boolean.TRUE);
        QueryWrapper<PmsPointLight> query = new QueryWrapper<>();
        if (dto.getId() != null) {
            query.eq("id", dto.getId());
        }
        if (dto.getBrandId() != null) {
            query.eq("brand_id", dto.getBrandId());
        }
        if (dto.getCategory() != null) {
            query.like("category", dto.getCategory());
        }
        query.groupBy("category");
        Page<PmsPointLight> result = pmsPointLightService.page(page, query);

        if (!ObjectUtils.isEmpty(result.getRecords())) {
            Map<Integer, PmsBrand> map = pmsBrandService.list().stream().collect(Collectors.toMap(PmsBrand::getId, brand -> brand));
            result.getRecords().forEach(e -> {
                if (map.get(e.getBrandId()) != null) {
                    e.setBrandName(map.get(e.getBrandId()).getName());
                }
            });

        }

        return CommonResult.success(result);
    }

    @ApiOperation("获取详情")
    @PostMapping("/detail")
    public CommonResult<IPage<PmsPointLight>> detail(@RequestBody PmsPointLightDTO dto) {
        if (StringUtils.isEmpty(dto.getCategory()) || dto.getBrandId() == null) {
            return CommonResult.failed(ResultCode.VALIDATE_FAILED);
        }
        Page<PmsPointLight> page = pmsPointLightService.page(new Page<>(dto.getPageNum(), dto.getPageSize(), Boolean.TRUE), new QueryWrapper<PmsPointLight>()
                .eq("brand_id", dto.getBrandId())
                .eq("category", dto.getCategory()));
        List<PmsPointLight> list = page.getRecords();
        list.sort(Comparator.comparing(PmsPointLight::getUrl));
        return CommonResult.success(page);
    }


    @ApiOperation("添加指示灯")
    @PostMapping("/add")
    public CommonResult<Void> addPointLight(@RequestBody PmsPointLight pmsPointLight) {
        List<String> urls = pmsPointLight.getUrls();
        if (ObjectUtils.isEmpty(urls)) {
            return CommonResult.failed(ResultCode.VALIDATE_FAILED);
        }
        List<PmsPointLight> data = new ArrayList<>();
        urls.forEach(url -> {
            PmsPointLight pointLight = new PmsPointLight();
            pointLight.setBrandId(pmsPointLight.getBrandId());
            pointLight.setCategory(pmsPointLight.getCategory());
            pointLight.setUrl(url);
            data.add(pointLight);
        });
        pmsPointLightService.saveBatch(data);
        return CommonResult.success(null);
    }

    @ApiOperation("批量删除指示灯")
    @DeleteMapping("/delete")
    public CommonResult<Void> deletePointLight(@RequestBody List<Integer> ids) {
        pmsPointLightService.removeByIds(ids);
        return CommonResult.success(null);
    }

    @ApiOperation("批量删除指示灯组下所有内容")
    @DeleteMapping("/deleteGroup")
    public CommonResult<Void> deleteGroupPointLight(@RequestBody List<PointLightDTO> dto) {
        for (PointLightDTO pointLightDTO : dto) {
            pmsPointLightService.remove(new QueryWrapper<PmsPointLight>().eq("brand_id", pointLightDTO.getBrandId())
                    .eq("category", pointLightDTO.getCategory()));
        }
        return CommonResult.success(null);
    }

    @Data
    public static class PointLightDTO {
        private Integer id;
        private Integer brandId;
        private String category;
        private String url;
    }

    @ApiOperation("修改指示灯")
    @PutMapping("/update")
    public CommonResult<Void> updatePointLight(@RequestBody PmsPointLight pmsPointLight) {
        pmsPointLightService.updateById(pmsPointLight);
        return CommonResult.success(null);
    }


    @Data
    public static class PmsPointLightDTO {
        private Integer id;
        private Integer brandId;
        private String category;
        private String url;

        private Integer pageNum = 1;
        private Integer pageSize = 10;
    }


}

